package com.mes.handler;

import com.eam.data.WmsDeliveryResultValue;
import com.mes.data.EmesColor;
import com.mes.data.EmesSize;
import com.mes.data.EmesVendor;
import com.mes.quality.data.EmesqInspectionItem;
import com.wms.entity.WmsDeliveryDetail;
import com.wms.entity.WmsStorageBatch;
import com.wms.entity.WmsStorageInOut;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.model.common.enterprise.Locator;
import org.openbravo.model.common.enterprise.Warehouse;
import org.openbravo.model.common.plm.Product;
import org.openbravo.model.common.uom.UOM;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;



/**
 * 录入检验结果
 */
public class QualityQueryResultHandler extends BaseActionHandler {
	private Logger logger = Logger.getLogger(this.getClass());

	@Override
	protected JSONObject execute(Map<String, Object> parameters, String data) {
		JSONObject jsonRep = new JSONObject();
		try {
			OBContext.setAdminMode();
			JSONObject reqData = new JSONObject(data);
			JSONArray jsonIds = reqData.getJSONArray("result");
			JSONObject temp = null;

			boolean flag = true;
			String failMsg = "";
			if (jsonIds != null && jsonIds.length() > 0) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

				Date time  =sdf.parse(sdf.format(new Date()));  //获取当前系统时间

				for (int i = 0; i < jsonIds.length(); i++) {
					temp = jsonIds.getJSONObject(i);

					long QtyError = temp.isNull("QTY_ERROR") ? 0 : temp.getInt("QTY_ERROR");//数量
					long QTYTEST = temp.isNull("QTY_TEST") ? 0 : temp.getInt("QTY_TEST");//数量
					long qty = temp.isNull("QTY") ? 0 : temp.getInt("QTY");

					String XMID = "";
					String WLID = "";
					String DETAILID = "";
					String CKID = "";
					String KWID = "";
					String DWID = "";
					String YSID = "";
					String CMID = "";
					String CGCODE = "";
					String CGID = "";
					String GYSID = "";
					String result = "";



					if(temp.has("XMID")){
						XMID = temp.getString("XMID");
					}
					if(temp.has("WLID")){
						WLID = temp.getString("WLID");
					}
					if(temp.has("DETAILID")){
						DETAILID = temp.getString("DETAILID");
					}
					if(temp.has("CKID")){
						CKID = temp.getString("CKID");
					}
					if(temp.has("KWID")){
						KWID = temp.getString("KWID");
					}
					if(temp.has("DWID")){
						DWID = temp.getString("DWID");
					}
					if(temp.has("YSID")){
						YSID = temp.getString("YSID");
					}
					if(temp.has("CMID")){
						CMID = temp.getString("CMID");
					}
					if(temp.has("CGCODE")){
						CGCODE = temp.getString("CGCODE");
					}
					if(temp.has("CGID")){
						CGID = temp.getString("CGID");
					}
					if(temp.has("GYSID")){
						GYSID = temp.getString("GYSID");
					}
					if(temp.has("RESULT")){
						result = temp.getString("RESULT");
					}

					WmsDeliveryDetail Detail = OBDal.getInstance().get(WmsDeliveryDetail.class, DETAILID);
					if("1".equals(result)){
						result = "合格";

						String status = "normal";
						Product WL = OBDal.getInstance().get(Product.class, WLID);
						EmesVendor gys = OBDal.getInstance().get(EmesVendor.class, GYSID);
						UOM uom = OBDal.getInstance().get(UOM.class, DWID);
						EmesColor color = OBDal.getInstance().get(EmesColor.class, YSID);
						EmesSize size = OBDal.getInstance().get(EmesSize.class, CMID);
						Warehouse ck =OBDal.getInstance().get(Warehouse.class, CKID);
						Locator kw =OBDal.getInstance().get(Locator.class, KWID);
					//	WmsDelivery cg = OBDal.getInstance().get(WmsDelivery.class, CGID);


						WmsStorageBatch batch = new WmsStorageBatch();

						batch.setProduct(WL);
						batch.setEmesVendor(gys);
						batch.setUom(uom);
						batch.setStatus(status);
						batch.setEmesColor(color);
						batch.setEmesSize(size);
						batch.setTime(time);

						OBDal.getInstance().save(batch);
						OBDal.getInstance().flush();

						BigDecimal a = new BigDecimal(QTYTEST);

						WmsStorageInOut  Storage = new WmsStorageInOut();
						Storage.setWmsStorageBatch(batch);
						Storage.setWarehouse(ck);
						Storage.setLocator(kw);
						Storage.setQty(a);
						Storage.setUom(uom);
						Storage.setOptCode(CGCODE);
						Storage.setData(CGID);
						Storage.setStatus("OK");
						OBDal.getInstance().save(Storage);



					} else {
						result = "不合格";
					}

					WmsDeliveryResultValue resultValue = new WmsDeliveryResultValue();

					EmesqInspectionItem resultValues = OBDal.getInstance().get(EmesqInspectionItem.class, XMID);



					//resultValue = OBDal.getInstance().get(WmsDeliveryResultValue.class, result_Value_Id);

					//修改 原始采购订单相关物料出库数量
					resultValue.setQty(qty);
					resultValue.setEmesqInspectionItem(resultValues);
					resultValue.setWmsDeliveryDetail(Detail);
					resultValue.setQtyError(QtyError);
					resultValue.setResult(result);
					OBDal.getInstance().save(resultValue);

					Detail.setStatus("OK");
					OBDal.getInstance().save(Detail);

				}
			} else {
				flag = false;
				failMsg = "";
			}
			if (flag) {
				OBDal.getInstance().commitAndClose();
				jsonRep.put("result", true);
				jsonRep.put("msg", "录入成功");
			} else {
				OBDal.getInstance().rollbackAndClose();
				jsonRep.put("result", false);
				jsonRep.put("msg", failMsg);
			}
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
			logger.error("录入失败：", e);
			try {
				jsonRep.put("result", false);
				jsonRep.put("msg", "录入失败，"+e.getMessage());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
		} finally {
			OBContext.restorePreviousMode();
		}
		return jsonRep;
	}
}